package com.meilai.project.service.business.contract.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.meilai.project.mapper.business.contract.ContractNumMapper;
import com.meilai.project.service.business.contract.BillNumberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author xchen
 * @since 2022-03-24
 */
@Service
public class BillNumberServiceImpl implements BillNumberService {

	@Autowired
	private ContractNumMapper contractNumMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String getNewContractNum(String type) {
		String contractNum = type + DateUtil.format(new Date(), "yyyy");
		Integer currentNum = getCurrentNum(type);
		String numStr = StrUtil.fillBefore(currentNum.toString(), '0', 4);
		return contractNum + numStr;
	}

	private Integer getCurrentNum(String type) {
		String year = DateUtil.format(new Date(), "yyyy");
		//如果不存在则初始化
		boolean hasExists = contractNumMapper.hasExists(type, year);
		if (!hasExists) {
			contractNumMapper.init(type, year);
		}
		//锁定这条记录，只能当前线程修改
		contractNumMapper.lock(type, year);
		//num+1
		contractNumMapper.increase(type, year);
		//查询最新num
		return contractNumMapper.getCurrNum(type, year);
	}
}
